/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.knet.sp.ncrm.modules.customer.potentialcustomer.service;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.knet.sp.ncrm.common.persistence.BaseEntity;
import cn.knet.sp.ncrm.common.persistence.Page;
import cn.knet.sp.ncrm.common.service.CrudService;
import cn.knet.sp.ncrm.common.service.ServiceException;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.modules.customer.aftersalesservice.entity.PotentialAfterSalesService;
import cn.knet.sp.ncrm.modules.customer.aftersalesservice.service.PotentialAfterSalesServiceService;
import cn.knet.sp.ncrm.modules.customer.importsupport.ImportService;
import cn.knet.sp.ncrm.modules.customer.potentialadmingroup.entity.PotentialAdminGroup;
import cn.knet.sp.ncrm.modules.customer.potentialadmingroup.service.PotentialAdminGroupService;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.dao.PotentialCustomerDao;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.dao.PotentialCustomerStatusDao;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.entity.PotentialCustomer;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.entity.PotentialCustomerAddinfo;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.entity.PotentialCustomerStatus;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.support.DistEnum;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.vo.PotentialCustomerVo;
import cn.knet.sp.ncrm.modules.customer.potentialdistrecord.entity.PotentialDistRecord;
import cn.knet.sp.ncrm.modules.customer.potentialdistrecord.service.PotentialDistRecordService;
import cn.knet.sp.ncrm.modules.customer.potentialgroup.entity.PotentialGroup;
import cn.knet.sp.ncrm.modules.customer.potentialgroup.service.PotentialGroupService;
import cn.knet.sp.ncrm.modules.sys.customerstatus.dao.CustomerStatusDao;
import cn.knet.sp.ncrm.modules.sys.customerstatus.entity.CustomerStatus;
import cn.knet.sp.ncrm.modules.sys.customerstatus.service.CustomerStatusService;
import cn.knet.sp.ncrm.modules.sys.user.entity.User;
import cn.knet.sp.ncrm.modules.sys.utils.CustomerUtils;
import cn.knet.sp.ncrm.modules.sys.utils.UserUtils;

/**
 * 潜在客户主表Service
 *
 * @author gehaiyang
 * @version 2015 -08-24
 * @since 2015 /09/02 16:13:37
 */
@Service
@Transactional(readOnly = true)
public class PotentialCustomerService extends CrudService<PotentialCustomerDao, PotentialCustomer> {

    /**
     * The Potential customer dao.
     */
    @Resource
    private PotentialCustomerDao potentialCustomerDao;

    @Resource
    private PotentialCustomerStatusDao potentialCustomerStatusDao;

    /**
     * The Potential dist record service.
     */
    @Resource
    private PotentialDistRecordService potentialDistRecordService;

    /**
     * The Potential admin group service.
     */
    @Resource
    private PotentialAdminGroupService potentialAdminGroupService;

    /**
     * The Potential group service.
     */
    @Resource
    private PotentialGroupService potentialGroupService;

    @Resource
    private PotentialAfterSalesServiceService afterSalesServiceService;
    @Resource
    private PotentialCustomerAddinfoService potentialCustomerAddinfoService;
    
    @Resource
    private CustomerStatusService customerStatusService;
    /**
     * 无意向数据解禁表达式
     */
    @Value("${customer.freeze.exp}")
    private String freeze_exp;

    @Resource
    private ImportService importService;

    public PotentialCustomer get(String id) {
        return super.get(id);
    }

    public PotentialCustomer get(PotentialCustomer potentialCustomer) {
        return this.dao.getByEntity(potentialCustomer);
    }

    public List<PotentialCustomer> findList(PotentialCustomer potentialCustomer) {
        if (potentialCustomer.getDistStatus() != null
                && potentialCustomer.getDistStatus().equals(DistEnum.UNDISTED.getValue())) {
            potentialCustomer.setFreezeExp(freeze_exp);
        }
        return super.findList(potentialCustomer);
    }

    public Page<PotentialCustomer> findPage(Page<PotentialCustomer> page, PotentialCustomer potentialCustomer) {
        if (potentialCustomer.getDistStatus() != null
                && potentialCustomer.getDistStatus().equals(DistEnum.UNDISTED.getValue())) {
            potentialCustomer.setFreezeExp(freeze_exp);
        }
        return super.findPage(page, potentialCustomer);
    }

    /**
     * <p>
     * 我的工作分页查询
     * </p>
     * 
     * @param page
     * @param potentialCustomer
     * @return
     */
    public Page<PotentialCustomer> findMyPage(Page<PotentialCustomer> page, PotentialCustomer potentialCustomer) {
        if (potentialCustomer.getDistStatus() != null
                && potentialCustomer.getDistStatus().equals(DistEnum.UNDISTED.getValue())) {
            potentialCustomer.setFreezeExp(freeze_exp);
        }
        potentialCustomer.setPage(page);
        page.setList(potentialCustomerDao.findMyList(potentialCustomer));
        return page;
    }

    /**
     * <p>
     * 获取非数据管理员的数据 add by jief 20170211
     * </p>
     * 
     * @param page
     * @param potentialCustomer
     * @return
     */
    public Page<PotentialCustomer> findSubPage(Page<PotentialCustomer> page, PotentialCustomer potentialCustomer) {
        if (potentialCustomer.getDistStatus() != null
                && potentialCustomer.getDistStatus().equals(DistEnum.UNDISTED.getValue())) {
            potentialCustomer.setFreezeExp(freeze_exp);
        }
        potentialCustomer.setPage(page);
        page.setList(potentialCustomerDao.findSubList(potentialCustomer));
        return page;
    }

    @Transactional(readOnly = false)
    public void save(PotentialCustomer potentialCustomerVo) {
        super.save(potentialCustomerVo);
    }

    /**
     * 修改基本信息
     *
     * @author Gehaiyang
     * @date 2015年9月11日 下午2:09:45
     */
    @Transactional(readOnly = false)
    public void modifyBasicInfo(PotentialCustomerVo potentialCustomerVo) {
        PotentialCustomer potentialCustomer = new PotentialCustomer();
        PotentialCustomerAddinfo addinfo = new PotentialCustomerAddinfo();
        try {
            BeanUtils.copyProperties(potentialCustomer, potentialCustomerVo);
            BeanUtils.copyProperties(addinfo, potentialCustomerVo);
        } catch (Exception e) {
            logger.error("给属性赋值出现错误", e);
            throw new ServiceException(e.getMessage());
        }
        potentialCustomer.setLastUpdated(new Date());
        potentialCustomerDao.updateBasicInfo(potentialCustomer);
        if (StringUtils.isNotBlank(potentialCustomerVo.getAddInfoId())) {
            addinfo.setId(potentialCustomerVo.getAddInfoId());
            addinfo.setIsNewRecord(false);
        }
        addinfo.setPotentialCustomerId(potentialCustomer.getId());
        potentialCustomerAddinfoService.save(addinfo);
    }

    @Transactional(readOnly = false)
    public void delete(PotentialCustomer potentialCustomer) {
        potentialCustomer.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
        super.delete(potentialCustomer);
        // 级联删除下级数据
        PotentialCustomerStatus status = new PotentialCustomerStatus();
        status.setFirsthandId(potentialCustomer.getId());
        potentialCustomerStatusDao.deleteByFirstHandId(status);
    }

    /**
     * <p>
     * 数据回收
     * </p>
     * 
     * @param potentialCustomer
     */
    @Transactional(readOnly = false)
    public void recovery(PotentialCustomer potentialCustomer) {
        potentialCustomerDao.recovery(potentialCustomer);
    }

    /**
     * 分配数据
     *
     * @param ids
     *            the ids
     * @param userIds
     *            the user ids
     * @author Gehaiyang
     * @date 2015年8月30日 下午5:56:07
     * @since 2015 /09/02 16:13:37
     */
    @Transactional(readOnly = false)
    public void distData(String[] ids, String[] userIds) {
        PotentialCustomer potentialCustomer = null;
        PotentialDistRecord potentialDistRecord = null;
        for (int i = 0, k = 0; i < ids.length; i++) {
            Date nowDate = new Date();
            // 封装主表需要更新的字段
            potentialCustomer = new PotentialCustomer();
            potentialCustomer.setId(ids[i]);
            potentialCustomer.setExecutorId(userIds[k]);
            potentialCustomer.setDistDate(nowDate);
            if ("thinkgem".equals("distUser.getLoginName()")) {
                potentialCustomer.setDistStatus("UNDISTED");
            } else {
                potentialCustomer.setDistStatus("DISTED");
            }
            potentialCustomer.setDistUserId(UserUtils.getUser().getId());
            potentialCustomer.setLastUpdated(nowDate);
            potentialCustomer.setCustomerStatusId("");
            potentialCustomer.setLastCustomerStatus("");
            // User user=UserUtils.get(userIds[k]);
            potentialCustomerDao.updateDistInfo(potentialCustomer);
            // 封装分配记录实体
            potentialDistRecord = new PotentialDistRecord();
            potentialDistRecord.setPotentialCustomerId(ids[i]);
            potentialDistRecord.setCreateUserId(potentialCustomer.getDistUserId());
            potentialDistRecord.setDateCreated(nowDate);
            potentialDistRecord.setExecutorId(potentialCustomer.getExecutorId());
            potentialDistRecord.setLastUpdated(nowDate);
            potentialDistRecord.setIsNewRecord(false);
            potentialDistRecordService.save(potentialDistRecord);
            k++;
            // 如果记录数大于分配的人数，当按人员每人一条分配完成后，继续从第一个人依次循环分配
            if (k == userIds.length) {
                k = 0;
            }
        }
    }

    /**
     * 新分配数据策略 上级分配数据给下级，下级仍然可以继续分配
     * 
     * @param ids
     *            the ids
     * @param userIds
     *            the user ids
     * @author jief
     * @date 2017年2月11日 下午8:56:07
     * @since 2017 /02/11 16:13:37
     */
    @Transactional(readOnly = false)
    public void newDistData(User distUser, String[] ids, String[] userIds) {
        PotentialCustomer potentialCustomer = null;
        PotentialDistRecord potentialDistRecord = null;
        for (int i = 0, k = 0; i < ids.length; i++) {
            Date nowDate = new Date();
            // 封装主表需要更新的字段
//            potentialCustomer = new PotentialCustomer();
//            potentialCustomer.setId(ids[i]);
//            potentialCustomer.setExecutorId(userIds[k]);
//            potentialCustomer.setDistDate(nowDate);
//            logger.info("distUser.getLoginName() is {} userType is {}, userWEight is {}, id is {}", distUser.getLoginName(),
//                    distUser.getUserType(), distUser.getUserWeight(), distUser.getId());
//            if ("thinkgem".equals("distUser.getLoginName()")) {
//                potentialCustomer.setDistStatus("UNDISTED");
//            } else {
//                potentialCustomer.setDistStatus("DISTED");
//            }
//            potentialCustomer.setDistUserId(UserUtils.getUser().getId());
//            potentialCustomer.setLastUpdated(nowDate);
//            potentialCustomer.setCustomerStatusId("");
//            potentialCustomer.setLastCustomerStatus("");
//            potentialCustomerDao.updateDistInfo(potentialCustomer);
            
            //--------------------------------
            potentialCustomer = new PotentialCustomer();
            potentialCustomer.setId(ids[i]);
            potentialCustomer.setExecutorId(userIds[k]);
            potentialCustomer.setDistDate(nowDate);
            potentialCustomer.setDistStatus("DISTED");
            potentialCustomer.setDistUserId(UserUtils.getUser().getId());
            potentialCustomer.setLastUpdated(nowDate);
            potentialCustomerDao.updateDistInfo(potentialCustomer);
//            PotentialCustomer potentialCustomerEntity = potentialCustomerDao.get(ids[i]);
//            potentialCustomerEntity.getCustomerStatusId();
//            String lastCustomerStatusId = potentialCustomerEntity.getLastCustomerStatusId();
//            customerStatusService
            logger.info("distUser.getLoginName() is {} userType is {}, userWEight is {}, id is {}", distUser.getLoginName(),
                  distUser.getUserType(), distUser.getUserWeight(), distUser.getId());
            // 插入分配的数据到status表，方便后续的继续分配
            User user = UserUtils.get(userIds[k]);
            if (!"3".equals(user.getUserType())) {
                logger.info("logger 3333333333333333333333333");
                System.out.println("333333333333333333333333333");
                PotentialCustomerStatus addStatus = new PotentialCustomerStatus();
                addStatus.setDistStatus("UNDISTED");
                addStatus.setVisibilityUserId(userIds[k]);
                addStatus.setFirsthandId(ids[i]);
                addStatus.setParentId(distUser.getId());
                addStatus.preInsert();
                potentialCustomerStatusDao.insert(addStatus);
            }
            
            // 销售总监或销售经理
            if (CustomerUtils.USER_TYPE_OFFICER.equals(distUser.getUserType())
                    || CustomerUtils.USER_TYPE_MANAGER.equals(distUser.getUserType())) {
                PotentialCustomerStatus findStatus = new PotentialCustomerStatus();
                findStatus.setVisibilityUserId(distUser.getId());
                findStatus.setFirsthandId(ids[i]);
                List<PotentialCustomerStatus> pcss = potentialCustomerStatusDao.getByUserIdAndCustomerId(findStatus);
                if (pcss != null && pcss.size() > 0) {
                    PotentialCustomerStatus customerStatus = pcss.get(0);
                    customerStatus.setDistStatus("DISTED");
                    customerStatus.setDistUserId(distUser.getId());
                    customerStatus.setExecutorName(user.getName());
                    customerStatus.setExecutorId(userIds[k]);
                    potentialCustomerStatusDao.update(customerStatus);
                    // 如果是销售经理的话还的修改销售总监的数据分配状态
                    if (CustomerUtils.USER_TYPE_MANAGER.equals(distUser.getUserType())) {
                        // PotentialCustomerStatus find_parent_status=new PotentialCustomerStatus();
                        findStatus.setVisibilityUserId(customerStatus.getParentId());
                        findStatus.setFirsthandId(ids[i]);
                        List<PotentialCustomerStatus> parent_pcss = potentialCustomerStatusDao
                                .getByUserIdAndCustomerId(findStatus);
                        if (parent_pcss != null && parent_pcss.size() > 0) {
                            PotentialCustomerStatus parent_status = parent_pcss.get(0);
                            parent_status.setDistStatus("DISTED");
                            parent_status.setDistUserId(distUser.getId());
                            parent_status.setExecutorId(userIds[k]);
                            potentialCustomerStatusDao.update(parent_status);
                        }
                    }
                }
            }
            // 封装分配记录实体
            potentialDistRecord = new PotentialDistRecord();
            potentialDistRecord.setPotentialCustomerId(ids[i]);
            potentialDistRecord.setCreateUserId(potentialCustomer.getDistUserId());
            potentialDistRecord.setDateCreated(nowDate);
            potentialDistRecord.setExecutorId(potentialCustomer.getExecutorId());
            potentialDistRecord.setLastUpdated(nowDate);
            potentialDistRecord.setIsNewRecord(false);
            potentialDistRecordService.save(potentialDistRecord);
            k++;
            // 如果记录数大于分配的人数，当按人员每人一条分配完成后，继续从第一个人依次循环分配
            if (k == userIds.length) {
                k = 0;
            }
        }
    }

    /**
     * 数据分组
     *
     * @param ids
     *            the ids
     * @param groupId
     *            the group id
     * @author Gehaiyang
     * @date 2015年8月30日 下午5:56:18
     * @since 2015 /09/02 16:13:37
     */
    @Transactional(readOnly = false)
    public void adminGroupData(String[] ids, String groupId) {
        PotentialCustomer potentialCustomer = new PotentialCustomer();
        if (groupId.equals("default")) {
            // 封装主表需要更新的字段
            potentialCustomer.setIds(ids);
            updateAdminGroupInfo(potentialCustomer);
            return;
        }
        // 查询分组信息，检测分组是否删除，同时获取父级分组
        PotentialAdminGroup potentialAdminGroup = potentialAdminGroupService.get(groupId);
        if (potentialAdminGroup != null && StringUtils.isNotBlank(potentialAdminGroup.getId())) {
            // 顶级分组
            if (potentialAdminGroup.getParentId().equals("0")) {
                potentialCustomer.setAdminGroup1Id(groupId);
                potentialCustomer.setRealAdminGroupId(groupId);
                potentialCustomer.setHasAdminGroup("yes");
            } else { // 第二级分组
                PotentialAdminGroup parentAdminGroup = potentialAdminGroupService
                        .get(potentialAdminGroup.getParentId());
                if (parentAdminGroup.getParentId().equals("0")) {
                    potentialCustomer.setAdminGroup1Id(parentAdminGroup.getId());
                    potentialCustomer.setAdminGroup2Id(groupId);
                    potentialCustomer.setRealAdminGroupId(groupId);
                    potentialCustomer.setHasAdminGroup("yes");
                } else {// 第三级分组
                        // 管理员分组最多分为3级，因此本次查询出的数据为最顶级分组
                    PotentialAdminGroup grandpaAdminGroup = potentialAdminGroupService
                            .get(parentAdminGroup.getParentId());
                    potentialCustomer.setAdminGroup1Id(grandpaAdminGroup.getId());
                    potentialCustomer.setAdminGroup2Id(parentAdminGroup.getId());
                    potentialCustomer.setAdminGroup3Id(groupId);
                    potentialCustomer.setRealAdminGroupId(groupId);
                    potentialCustomer.setHasAdminGroup("yes");
                }
            }
            // 封装主表需要更新的字段
            potentialCustomer.setIds(ids);
            updateAdminGroupInfo(potentialCustomer);
        } else {
            throw new ServiceException("选择的分组已被删除");
        }
    }

    /**
     * 更新用户的分组
     *
     * @param ids
     *            the ids
     * @param groupId
     *            the group id
     * @author 冯亚鹏
     * @date 2015年8月30日 下午5:56:18
     * @since 2015 /09/02 16:13:37
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Transactional(readOnly = false)
    public void updateGroup(String[] ids, String groupId) {
        Date nowDate = new Date();
        Map map = new HashMap();
        map.put("lastUpdated", nowDate);
        map.put("updateIds", ids);
        if (groupId.equals("default")) {
            for (int i = 0; i < ids.length; i++) {
                // 封装主表需要更新的字段
                map.put("group1", null);
                map.put("group2", null);
                map.put("realGroup", null);
                map.put("hasGroup", "no");
                this.dao.updateGroupInfo(map);
            }
            return;
        }
        // 查询分组信息，检测分组是否删除，同时获取父级分组
        PotentialGroup potentialGroup = potentialGroupService.get(groupId);
        map.put("realGroup", potentialGroup.getId());
        map.put("hasGroup", "yes");
        if (potentialGroup != null && StringUtils.isNotBlank(potentialGroup.getId())) {
            // 顶级分组
            if (potentialGroup.getParentId().equals("0")) {
                map.put("group1", potentialGroup.getId());
                map.put("group2", null);
            } else { // 第二级分组
                PotentialGroup parentPotentialGroup = potentialGroupService.get(potentialGroup.getParentId());
                if (parentPotentialGroup.getParentId().equals("0")) {
                    map.put("group1", potentialGroup.getParentId());
                    map.put("group2", potentialGroup.getId());
                }
            }
            this.dao.updateGroupInfo(map);
        } else {
            throw new ServiceException("选择的分组已被删除");
        }
    }

    /**
     * 更新分组信息
     *
     * @param potentialCustomer
     *            the potential customer
     * @author Gehaiyang
     * @date 2015年8月30日 下午5:56:47
     * @since 2015 /09/02 16:13:37
     */
    @Transactional(readOnly = false)
    public void updateAdminGroupInfo(PotentialCustomer potentialCustomer) {
        potentialCustomer.setLastUpdated(new Date());
        potentialCustomerDao.updateAdminGroupInfo(potentialCustomer);
    }

    /**
     * 删除管理员分组
     *
     * @param potentialAdminGroup
     *            the potential admin group
     * @author Gehaiyang
     * @date 2015年8月29日 下午4:50:38
     * @since 2015 /09/02 16:13:37
     */
    @Transactional(readOnly = false)
    public void deleteAdminGroup(PotentialAdminGroup potentialAdminGroup) {
        PotentialAdminGroup tempAdminGroup = potentialAdminGroupService.get(potentialAdminGroup.getId());
        if (tempAdminGroup != null && StringUtils.isNotBlank(tempAdminGroup.getId())) {
            try {
                // 根据分组level设置potentialCustomer对应字段的值
                PotentialCustomer potentialCustomer = new PotentialCustomer();
                Class<?> clazz = potentialCustomer.getClass();
                Field field = clazz.getDeclaredField("adminGroup" + tempAdminGroup.getLevelNum() + "Id");
                field.setAccessible(true);
                field.set(potentialCustomer, tempAdminGroup.getId());
                updateAdminGroupInfo(potentialCustomer);// 更新数据到未分组
                potentialAdminGroupService.delete(potentialAdminGroup);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new ServiceException("执行删除分组出现问题，删除失败");
            }
        } else {
            throw new ServiceException("分组已经被删除");
        }
    }

    /**
     * 合并数据
     *
     * @param potentialCustomer
     *            the potential customer
     * @author Gehaiyang
     * @date 2015年9月1日 下午3:30:32
     * @since 2015 /09/02 16:13:37
     */
    @Transactional(readOnly = false)
    public void mergerData(PotentialCustomer potentialCustomer) {
        potentialCustomer.setLastUpdated(new Date());
        // 更新主数据合并及未读数量
        potentialCustomerDao.updateMergerNum(potentialCustomer);
        // 合并数据
        potentialCustomerDao.mergerData(potentialCustomer);
    }

    /**
     * 批量修改
     *
     * @author Gehaiyang
     * @date 2015年9月8日 下午4:09:29
     */
    @Transactional(readOnly = false)
    public void batchEditData(PotentialCustomer potentialCustomer, PotentialAfterSalesService afterSalesService)
            throws InvocationTargetException, IllegalAccessException {
        // 修改潜在客户信息
        int userWeight = UserUtils.getUser().getUserWeight();
        if (potentialCustomer.getWeight() != null) {
            potentialCustomer
                    .setWeight(potentialCustomer.getWeight() > userWeight ? userWeight : potentialCustomer.getWeight());
        }
        if (StringUtils.isNotBlank(potentialCustomer.getCustomerStatusId())) {// 无效数据 0
            CustomerStatus customerStatus = CustomerUtils.getStatus(potentialCustomer.getCustomerStatusId());
            if (org.apache.commons.lang3.StringUtils.equals("无效数据", customerStatus.getContent())) {
                potentialCustomer.setWeight(0);
            }
        }
        if (!StringUtils.isBlank(afterSalesService.getTargetproducts())) {// 保存成单信息
            afterSalesService.setfIds(potentialCustomer.getIds());
            // 增加成单信息
            afterSalesServiceService.batchSaveData(afterSalesService);
            potentialCustomer.setWeight(100);// 成单 的权重为100
        }

        if (StringUtils.isNotBlank(potentialCustomer.getSource())
                || StringUtils.isNotBlank(potentialCustomer.getSourceDesc())
                || StringUtils.isNotBlank(potentialCustomer.getCustomerFeatureId())
                || StringUtils.isNotBlank(potentialCustomer.getCustomerTypeId())
                || StringUtils.isNotBlank(potentialCustomer.getMobileOrPc())
                || StringUtils.isNotBlank(potentialCustomer.getTargetProducts())
                || StringUtils.isNotBlank(potentialCustomer.getIndustry())
                || StringUtils.isNotBlank(potentialCustomer.getProvinceId()) || potentialCustomer.getWeight() != null
                || StringUtils.isNotBlank(potentialCustomer.getContactorPosition())
                || potentialCustomer.getDateCreated() != null || potentialCustomer.getLastUpdated() != null
                || StringUtils.isNotBlank(potentialCustomer.getCustomerStatusId())) {
            PotentialAdminGroup adminGroup = this.potentialAdminGroupService.getByName("成单数据");
            if (!StringUtils.isBlank(afterSalesService.getTargetproducts())) {// 成单信息不为空
                ArrayList<PotentialCustomer> recoverList = new ArrayList<>();// 成单后，进入回收流程进行数据合并
                for (String id : potentialCustomer.getIds()) {// 批量进行回收流程
                    PotentialCustomer tempPotentialCustomer = this.dao.get(id);
                    if (adminGroup != null) {// 设置成单分组
                        tempPotentialCustomer.setAdminGroup(adminGroup.getId(), null, null);
                    }
                    recoverList.add(tempPotentialCustomer);
                }
                importService.recover(recoverList);
            }
            potentialCustomerDao.updateBatchInfo(potentialCustomer);// 批量修改基本信息
        }
    }

    /**
     * 更新未读数量
     *
     * @author Gehaiyang
     * @date 2015年9月11日 上午9:19:44
     */
    @Transactional(readOnly = false)
    public void modifyNoReadNum(PotentialCustomer potentialCustomer) {
        if (null != potentialCustomer.getNoReadMergerNum() && potentialCustomer.getNoReadMergerNum() != 0) {
            // 更新未读数据量
            potentialCustomer.setNoReadMergerNum(0);
            potentialCustomer.setLastUpdated(new Date());
            potentialCustomerDao.updateMergerNum(potentialCustomer);
        }
    }

    /**
     * 获取详细信息
     *
     * @author fengyapeng
     * @since 2015 /08/29 16:21:42
     */
    @Transactional(readOnly = false)
    public PotentialCustomerVo getDetail(PotentialCustomer potentialCustomer) {
        return this.potentialCustomerDao.getDetail(potentialCustomer);
    }

    /**
     * 分解逻辑,parent.id 一定为null， 其他需要更改的，再设置
     *
     * @param potentialCustomer
     *            the potential customer
     * @author fengyapeng
     * @since 2015 /08/29 16:21:42
     */
    @Transactional(readOnly = false)
    public void resolvePotentialCustomer(PotentialCustomer potentialCustomer) {
        Date nowDate = new Date();
        // 查询主数据，更新重复数据量
        PotentialCustomer parent = get(potentialCustomer.getParent());
        parent.setMergerNum(parent.getMergerNum() - 1);
        parent.setLastUpdated(nowDate);
        potentialCustomerDao.updateMergerNum(parent);
        Integer flag = potentialCustomer.getFlag();// flag ==1 标识从我的客户，0 标识客户管理。
        if (flag != null && flag == 1) {// 从我的客户来的,分配状态为已分配，分配人为当前用户
            potentialCustomer.setDistStatus(DistEnum.DISTED.getValue());
            potentialCustomer.setExecutorId(UserUtils.getUser().getId());
        } else { // 系统过来的
            if (!StringUtils.isBlank(parent.getExecutorId())) {// 如果当前的客户已经分配了，则这个分解数据分给这个执行人
                potentialCustomer.setDistStatus(DistEnum.DISTED.getValue());
                potentialCustomer.setExecutorId(parent.getExecutorId());
            }
        }
        // 分解重复数据
        potentialCustomer.setMergerNum(0);
        potentialCustomer.setNoReadMergerNum(0);
        potentialCustomer.setLastUpdated(nowDate);
        potentialCustomer.clearGroup();
        potentialCustomer.clearAdminGroup();
        potentialCustomer.setParent(null);
        potentialCustomer.setLastUpdated(nowDate);
        this.potentialCustomerDao.update(potentialCustomer);
    }

    /**
     * 查询指定执行人，指定客户状态的 客户数量
     *
     * @param executorIds
     *            the executor id
     * @param customerStatusIds
     *            the customers ids
     * @return the int
     * @author fengyapeng
     * @since 2015 /09/10 18:39:37
     */
    public int countByCustomerStatusIds(ArrayList<String> executorIds, ArrayList<String> customerStatusIds) {
        Map map = new HashMap();
        map.put("executorIds", executorIds);
        map.put("customerStatusIds", customerStatusIds);
        return this.potentialCustomerDao.countByCustomerStatusIds(map);
    }

    /**
     * 查询指定执行人，指定客户状态的 客户，无分页
     *
     * @param executorIds
     *            the executor ids
     * @param customersStatusIds
     *            the customers status ids
     * @author fengyapeng
     * @since 2015 /09/11 15:33:39
     */
    public List<PotentialCustomer> findListByCustomerStatusIds(ArrayList<String> executorIds,
            ArrayList<String> customersStatusIds) {
        Map map = new HashMap();
        map.put("executorIds", executorIds);
        map.put("customerStatusIds", customersStatusIds);
        return this.potentialCustomerDao.findListByCustomerStatusIds(map);
    }
}